package com.elock.util;

import java.util.HashMap;
import java.util.Map;

import com.elock.base.core.util.SpringUtils;
import com.elock.service.SystemParameterBaseService;

/**
 * 系统配置
 * @author 仁德
 */
public class SystemConfig {

	/** 保存全局属性值 */
	private static Map<Long, HashMap<String, String>> map = new HashMap<Long, HashMap<String, String>>();

	private static Object lock = new Object();

	private SystemConfig() {}

	/**
	 * 根据参数编码 获取参数值
	 * 
	 * @param key
	 *            参数编码
	 * @param companyid
	 *            参数值
	 * @return
	 */
	public static String getConfig(String key, Long companyid) {

		if (key == null || key.trim().equals("") || companyid == null || companyid == 0) {
			throw new RuntimeException("获取参数值，传递的参数名有误！");
		}

		HashMap<String, String> value = map.get(companyid);

		if (value == null) {
			synchronized (lock) {// 防止并发设置
				value = map.get(companyid);
				if (value == null) {
					value = new HashMap<String, String>();
					map.put(companyid, value);
				}
			}
		}

		String result = value.get(key);

		if (result == null) {
			synchronized (lock) {// 防止并发设置
				result = value.get(key);
				if (result == null) {

					// 查询数据库，获取到具体参数值
					result = selSysConfig(key, companyid);

					if (result == null)
						throw new RuntimeException("参数编码[" + key + "]，系统中不存在,请联系管理员！");

					value.put(key, result);
				}
			}
		}

		return result;
	}

	/**
	 * 修改参数值，更新缓存值
	 * 
	 * @param key
	 * @param companyid
	 * @return
	 */
	public static void updateMap(String key, String svalue, Long companyid) {

		if (key == null || key.trim().equals("") || companyid == null || companyid == 0) {
			throw new RuntimeException("获取参数值，传递的参数名有误！");
		}

		HashMap<String, String> value = map.get(companyid);

		if (value == null) {
			synchronized (lock) {// 防止并发设置
				value = map.get(companyid);
				if (value == null) {
					value = new HashMap<String, String>();
					map.put(companyid, value);
				}
			}
		}

		synchronized (lock) {// 防止并发设置
			value.put(key, svalue);
		}

	}

	private static String selSysConfig(String key, Long companyid) {

		SystemParameterBaseService systemParameterService = SpringUtils.getBean(
				"systemParameterBaseServiceImpl", SystemParameterBaseService.class);
		return systemParameterService.getValue(companyid, key);
	}

}
